#!/usr/bin/env bash
# yitong.bai@qq.com

# 我是root用户吗？
function AmIRoot() {
  [[ $(id -u) -eq 0 ]] || return 1
}

# 我能连接到互联网吗？
function MayIAccessTheInternet() {
  if ! ping -c 1 www.baidu.com > /dev/null;then
    return 1
  fi
}

# 获取当前系统的id，centos还是ubuntu，返回字符串
function GetOperatingSystemId() {
  grep "^ID=" /etc/os-release | awk -F "=" '{print $2}' \
  | sed -e 's/^["]*//g' | sed -e 's/["]*$//g'
}

# 根据系统版本加载对应的库
function LoadFunctionsByOperatingSystemId() {
  local operatingSystemId=$(GetOperatingSystemId)
  local configTemp=$(mktemp)
  
  find "${LIB_DIR}/${operatingSystemId}" -type f > "${configTemp}"
  while IFS= read -r item; do
    source "${item}"
  done < "${configTemp}"
  rm -f "${configTemp}"
}

# 根据系统版本加载对应的库
function LoadRolesByOperatingSystemId() {
  local operatingSystemId=$(GetOperatingSystemId)
  local configTemp=$(mktemp)
  
  find "${ROLE_DIR}" -type f -name "*-${operatingSystemId}.sh" -or -name "main.sh"> "${configTemp}"
  while IFS= read -r item; do
    source "${item}"
  done < "${configTemp}"
  rm -f "${configTemp}"
}

# 获取当前节点主机名
function GetDefaultHostName() {
  export DEFAULT_HOSTNAME=$( hostname )
}

# 获取当前节点默认网卡IP地址
function GetDefaultIpAddress() {
  local defaultInterfaceName=$( ip route | grep default | awk '{print $5}' )
  export DEFAULT_IPADDRESS=$( ip a s "${defaultInterfaceName}" | grep "inet " |awk '{print $2}'  | awk -F "/" '{print $1}' )
}

# 加载配置文件
function LoadGaeaConfiguration() {
  local config="${CONF_DIR}/gaea.conf"
  local configTemp=$(mktemp)
  
  grep -E -v "^#|^$| .*" "${config}" > "${configTemp}"
  while IFS= read -r item; do
    export "${item}"
  done < "${configTemp}"
}

# 配置一个pip源
function ConfigurePipConfiguration() {
  local indexUrl="${1}"
  local trustedHost="${2}"

  cat > ~/.pip/pip.conf <<EOF
[global]
index-url = ${indexUrl}
[install]
trusted-host = ${trustedHost}
EOF
}

# 将系统自带的pip配置文件备份，放到bak/目录下
function BackupPipConfiguration() {
  mkdir -p ~/.pip/
  if [[ -f ~/.pip/pip.conf ]];
  then
    mv ~/.pip/pip.conf ~/.pip/pip.conf.bak."$(date "+%F_%R:%S")"
  fi
}

# Functions for docker
function RemoveDockerData() {
  systemctl stop docker &> /dev/null || continue
  [ "$#" -eq 0 ] && rm -rf /var/lib/docker \
  || \
  (
    local dataRoot="${1}"
    [ -n "${dataRoot}" ] && rm -rf "${dataRoot}"
  )
}

function RemoveDockerDaemonJson() {
  systemctl stop docker &> /dev/null || continue
  rm -rf /etc/docker/daemon.json
}

function DockerSaveImages() {
  local dataPath="${1}"
  local dockerImages="${2}"

  mkdir -p "${dataPath}" && cd "${dataPath}"

  docker images | grep -v "^REPOSITORY" | awk '{print $1":"$2}' > "${dockerImages}"
  while IFS= read -r docker_image; do
    docker_image_file_name=$(echo "${docker_image}" | awk -F ":" '{print $1}' | awk -F "/" '{print $NF}').tar
    docker save "${docker_image}" -o "${docker_image_file_name}"
  done < "${dockerImages}"
}

function DockerLoadRetagAndPushImages() {

  local dataPath="$1"
  local dockerImages="$2"
  local new_registry_name="$3"

  check_docker_if_is_existed

  cd "${dataPath}" || return
  for f in *.tar;
  do
    info "*** loading docker image ${f} ***"
    docker load -i "${f}" &> /dev/null
  done

  while IFS= read -r docker_image; do
    if [[ "${docker_image}" =~ "nginx" ]]; then
      new_docker_image="${new_registry_name}/library/${docker_image}"
    else
      new_docker_image="${new_registry_name}/${docker_image}"
    fi

    info "*** docker tag ${docker_image} as ${new_docker_image} ***"
    docker tag "${docker_image}" "${new_docker_image}" &> /dev/null
    info "*** pushing ${new_docker_image}"
    docker push "${new_docker_image}" &> /dev/null
  done < "${dockerImages}"

  remove_docker_daemonjson
}

# 更改要下载的Kubernetes集群版本
function ChangeDownloadKubernetesVersion() {
  local dataPath="${1}"
  local kubeVersion="${2}"
  local kubesprayDefaultEnvFile="${dataPath}/roles/kubespray-defaults/defaults/main.yaml"
  
  sed -i "s#^kube_version: .*#kube_version: ${kubeVersion}#" "${kubesprayDefaultEnvFile}"
}

# 对release_dir重新命名以适配kubespray download role
function RenameKubernetesReleaseDir() {

  local dataPath="${1}"

  local kubesprayDownloadEnvFile="${dataPath}/kubespray/roles/download/defaults/main.yml"
  local kubesprayDefaultEnvFile="${dataPath}/kubespray/roles/kubespray-defaults/defaults/main.yaml"
  local releaseDir="${dataPath}/release"
  local imageArch="amd64"

  # etcd => kubesprayDownloadEnvFile
  #etcd_version=$(grep "^etcd_version" "${kubesprayDownloadEnvFile}" | awk '{print $2}' | sed $'s/\"//g' )

  # cni => kubesprayDownloadEnvFile
  cni_version=$(grep "^cni_version:" "${kubesprayDownloadEnvFile}" | awk '{print $2}' | sed $'s/\"//g')
  cni_dst_dir="${dataPath}/containernetworking/plugins/releases/download/${cni_version}"
  cni_src_filename="cni-plugins-linux-${imageArch}-${cni_version}.tgz"
  cni_dst_filename="cni-plugins-linux-${imageArch}-${cni_version}.tgz"

  rm -rf "${cni_dst_dir}" && mkdir -p "${cni_dst_dir}"
  /bin/mv -f "${releaseDir}/${cni_src_filename}" "${cni_dst_dir}/${cni_dst_filename}"

  # calico => kubesprayDownloadEnvFile
  calico_ctl_version=$(grep "^calico_version:" ${kubesprayDownloadEnvFile} | awk '{print $2}' | sed $'s/\"//g')
  calico_ctl_dst_dir="${dataPath}/projectcalico/calicoctl/releases/download/${calico_ctl_version}"
  calico_ctl_src_filename="calicoctl"
  calico_ctl_dst_filename="calicoctl-linux-${imageArch}"

  rm -rf "${calico_ctl_dst_dir}" && mkdir -p "${calico_ctl_dst_dir}"
  /bin/mv -f "${releaseDir}/${calico_ctl_src_filename}" "${calico_ctl_dst_dir}/${calico_ctl_dst_filename}"

  # kubectl => kubesprayDefaultEnvFile
  # kubelet => kubesprayDefaultEnvFile
  # kubeadm => kubesprayDefaultEnvFile
  kube_version=$(grep "^kube_version:" ${kubesprayDefaultEnvFile} | awk '{print $2}' )
  kube_dst_dir="${dataPath}/kubernetes-release/release/${kube_version}/bin/linux/${imageArch}"

  rm -rf "${kube_dst_dir}" && mkdir -p "${kube_dst_dir}"
  /bin/mv -f "${releaseDir}/kubeadm-${kube_version}-${imageArch}" "${kube_dst_dir}/kubeadm"
  /bin/mv -f "${releaseDir}/kubectl-${kube_version}-${imageArch}" "${kube_dst_dir}/kubectl"
  /bin/mv -f "${releaseDir}/kubelet-${kube_version}-${imageArch}" "${kube_dst_dir}/kubelet"

  # Delete Kubespray Release Dir
  rm -rf "${releaseDir}"
}